package com.dk.controller;

import com.dk.data.Result;
import com.dk.data.ResultEnum;
import com.dk.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("weather")
public class Weather {

    @RequestMapping("getWeather")
    @ResponseBody
    public Result getWeather() {
        String host = "https://weather01.market.alicloudapi.com";
        String path = "/ip-to-weather";
        String method = "GET";
        String appcode = "3e0d061ca3cb479dab148480f02b2364";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("ip", "111.36.195.178");
        querys.put("need3HourForcast", "0");
        querys.put("needAlarm", "0");
        querys.put("needHourData", "0");
        querys.put("needIndex", "0");
        querys.put("needMoreDay", "0");


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            String string = EntityUtils.toString(response.getEntity());
            return Result.response(ResultEnum.OK).setData(string);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.response(ResultEnum.FAIL);
        }

    }

}
